package 美团;

import 链表.ListNode;

public class _25_K个一组翻转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummyhead = new ListNode(0);
        ListNode left = dummyhead;
        ListNode right = dummyhead;

        while (right != null) {
            int step = 0;
            while (right != null && step < k - 1) {
                right = right.next;
                step++;
            }
            if (right == null) break;
            // right指向需要倒置链表的末端，left指向需要倒置链表的前一个节点。
            right = right.next;
            ListNode nextLeft = left.next;

            ListNode index = left.next;
            left.next = null;
            while (index != right.next) {
                ListNode temp = index;
                index = index.next;
                temp.next = left.next;
                left.next = temp;
            }

            left = nextLeft;
        }
        return null;
    }
}
